package com.atguigu.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * UserController
 *
 * @author yangchao
 * @version 开发阶段
 * @description TODO
 * @date 2022/3/2 9:47
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserInfoService userService;
    @Resource
    private RedisTemplate redisTemplate;

    private final static  String  USER_VIEWS="USER-VIEWS";
    @PostMapping("/login")
    public RetVal login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        UserInfo dbUser = userService.queryUserFromDb(userInfo);
        if (dbUser!=null){
            //1.返回给页面信息的map
            HashMap<String, Object> retMap = new HashMap<>();
            //2.制作一个token
            String token = UUID.randomUUID().toString();
            retMap.put("token",token);
            //3.把用户昵称信息也放入
            retMap.put("nickName",dbUser.getNickName());
            //4.将用户信息存储缓存！
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX+token;
            //5.userId用于判断是否登录,ip地址用于判断是否为同一台电脑登录
            JSONObject loginInfo = new JSONObject();
            loginInfo.put("userId",dbUser.getId().toString());
            loginInfo.put("loginIp", IpUtil.getIpAddress(request));
//            redisTemplate.opsForValue().set(userKey,loginInfo.toJSONString(), RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(userKey,loginInfo.toJSONString(),RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
            redisTemplate.opsForZSet().incrementScore(USER_VIEWS, "skuId:" + dbUser.getId().toString(), 1);
            return RetVal.ok(retMap);
        }else {
            return RetVal.fail().message("登录失败！");
        }
    }
    @PostMapping("/register")
    public RetVal register(@RequestBody UserInfo userInfo, HttpServletRequest request){
        userInfo.setHeadImg("1");
        userInfo.setUserLevel("2");
        userInfo.setPasswd(DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
        userService.save(userInfo);
        return RetVal.ok();

    }


    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request){
        String userKey=RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token");
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }


}
